package com.cbtx.tablet.ui

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SPUtils
import com.cbtx.networklib.ContextManager
import com.cbtx.tablet.App
import com.cbtx.tablet.BuildConfig
import com.cbtx.tablet.R
import com.cbtx.tablet.bean.Report
import com.cbtx.tablet.constant.HttpConstant
import com.cbtx.tablet.device.IMachine
import com.cbtx.tablet.device.MachineFactory
import com.cbtx.tablet.dialog.TipsDialog
import com.cbtx.tablet.exception.RequestException
import com.cbtx.tablet.net.HttpResponse
import com.cbtx.utils.DeviceUtil
import com.cbtx.utils.zxing.ZxingUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_start.*
import java.util.concurrent.TimeUnit

class StartActivity : AbsBaseActivity() {

    private var dispose: Disposable? = null

    lateinit var tipsDialog: TipsDialog

    private var topClickTime: Long = 0
    private var topClickCount = 0
    private var isIntoMainActivity = false

    override fun layoutId(): Int = R.layout.activity_start

    override fun initView(savedInstanceState: Bundle?) {
        tv_device_code.text = "云屏编码:${App.androidId}"
        iv_to_net_set.setOnLongClickListener {
            toNetSet()
            return@setOnLongClickListener true
        }

        iv_to_system_set.setOnClickListener {
            val time2 = System.currentTimeMillis() - topClickTime
            if (time2 > 1500) {
                topClickCount = 1
            } else {
                topClickCount++
            }
            if (topClickCount >= 10) {
                val localIntent = Intent(Settings.ACTION_SETTINGS)
                startActivity(localIntent)
                topClickCount = 0
            }
            topClickTime = System.currentTimeMillis()
        }
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    override fun onStart() {
        super.onStart()
        isIntoMainActivity = false
        checkNet()
    }

    private fun checkNet() {
        if (SPUtils.getInstance().getBoolean("isBind")) {
            startActivity(Intent(this, MainActivity::class.java))
        } else {
            if (NetworkUtils.isConnected()) {
                dispose = Observable.interval(0, 10, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        report()
                    }
            } else {
                showNoNet()
            }
        }
    }

    private fun getQRImage(): Bitmap? {
        val wh: Int = ContextManager.getContext().resources.getDimensionPixelSize(R.dimen.dp_400)
        val iMachine: IMachine =
            MachineFactory.getAutoCreate(App.instance)

        var url = if (BuildConfig.DEBUG) {
            ContextManager.getContext().getString(
                R.string.register_qr,
                "t.mj.linkzl.com",
                if (TextUtils.isEmpty(DeviceUtil.getSerial(this))) "" else DeviceUtil.getSerial(this),
                MachineFactory.getAutoCreate(ContextManager.getContext()).uniqueDeviceCode,
                "INTERACTIVE",
                iMachine.localMac,
                iMachine.model
            )
        } else {
            ContextManager.getContext().getString(
                R.string.register_qr,
                "ad.mjcmkj.com",
                if (TextUtils.isEmpty(DeviceUtil.getSerial(this))) "" else DeviceUtil.getSerial(this),
                MachineFactory.getAutoCreate(ContextManager.getContext()).uniqueDeviceCode,
                "INTERACTIVE",
                iMachine.localMac,
                iMachine.model
            )
        }

        return ZxingUtils.createQRCode(
            url,
            wh,
            BitmapFactory.decodeResource(resources, R.mipmap.ic_logo_qr_code)
        )
    }

    private fun register() {
        var map = mutableMapOf<String, Any>()
        map["lastRebootTime"] = App.bootTime
        map["packageName"] = packageName(App.instance)
        App.sApiServiceHolder.getApiService(HttpConstant.CONTENT_ALIAS)
            .register(map)
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            //请求失败重连次数
            .retry(2)
            .subscribeBy(
                onError = {
                    LogUtils.e("注册失败")
                },
                onNext = {
                    if (!isIntoMainActivity) {
                        isIntoMainActivity = true
                        startActivity(Intent(this, MainActivity::class.java))
                    }
                }
            )
    }

    private fun authFail() {
        SPUtils.getInstance().put("isBind", false)
        ll_container.visibility = View.VISIBLE
        iv_qr_code_display.setImageBitmap(getQRImage())
    }

    override fun reportSuccess(result: HttpResponse<Report>?) {

        when (result?.code) {
            RequestException.CODE_DEVICE_DID_NOT_REGISTER -> {
                register()
            }
            RequestException.CODE_PERMISSION_DENIED,
            RequestException.CODE_DEVICE_TOKEN_INVALID,
            RequestException.CODE_DEVICE_IS_FROZEN,
            RequestException.CODE_COMPANY_OUT_OF_SERVICE -> {
                authFail()
            }
            else -> {
                SPUtils.getInstance().put("isBind", true)
                dispose?.apply {
                    if (!this.isDisposed) {
                        this.dispose()
                    }
                }
                if (!isIntoMainActivity) {
                    isIntoMainActivity = true
                    startActivity(Intent(this, MainActivity::class.java))
                }
            }
        }
    }

    // u、无网弹窗
    private fun showNoNet() {
        tipsDialog = TipsDialog(this)
        tipsDialog
            .setContent("哎呀，暂无网络，请前往设置")
            .setAgree("前往设置")
            .setOnDialogListener(object : TipsDialog.OnDialogListener {
                override fun onCancel() {

                }

                override fun onAgree() {
                    tipsDialog.dismiss()
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        val panelIntent = Intent(Settings.Panel.ACTION_WIFI)
                        startActivityForResult(panelIntent, REQUEST_WIFI_SET)
                    } else {
                        val intent = Intent()
                        intent.action = "android.net.wifi.PICK_WIFI_NETWORK"
                        intent.putExtra(":settings:show_fragment_as_subsetting", true)
                        startActivityForResult(intent, REQUEST_WIFI_SET)
                    }
                }
            })
        tipsDialog.show()
    }
}